<template>
  <view>
    <view class="page-content">
      <view class="form-show">
        <u-form :model="form" ref="refForm" :error-type="['toast']">
          <text class="font-bold u-font-32 u-content-color">审批结果</text>
          <u-form-item prop="result">
            <u-card :show-head="false" :show-foot="false">
              <template #body>
                <cellSelectGroup
                  v-model:value="form.result"
                  type="radio"
                  @change="resultChange"
                >
                  <cellSelectItem :value="1">同意</cellSelectItem>
                  <cellSelectItem v-if="!hideReturn" :value="0"
                    >退回</cellSelectItem
                  >
                  <cellSelectItem v-if="[3].includes(taskType)" :value="2"
                    >拒绝</cellSelectItem
                  >
                </cellSelectGroup>
              </template>
            </u-card>
          </u-form-item>
          <u-form-item v-if="form.result === 1 && form.nodeId">
            <text class="u-m-b-20 block font-bold u-font-32 u-content-color"
              >下一节点审批人</text
            >
            <view class="next-point">
              <u-cell-group>
                <u-cell-item @click="showMember()">
                  <template #title>
                    <text v-if="labels.length && labels[0]">{{
                      labels.join(',')
                    }}</text>
                    <text class="error" v-else>未设置</text>
                  </template>
                </u-cell-item>
              </u-cell-group>
            </view>
          </u-form-item>
          <u-form-item v-if="form.result === 0 && targetKeyName">
            <text class="block font-bold u-font-32 u-content-color"
              >退回节点</text
            >
            <view class="next-point">
              <u-cell-group>
                <u-cell-item title="退回至" :arrow="false">
                  <template #right-icon>
                    <text class="error">{{ targetKeyName }}</text>
                  </template>
                </u-cell-item>
              </u-cell-group>
            </view>
          </u-form-item>
          <u-form-item v-if="form.result === 2">
            <text class="block font-bold u-font-32 u-content-color"
              >拒绝节点</text
            >
            <view class="next-point">
              <u-cell-group>
                <u-cell-item title="" :arrow="false">
                  <template #right-icon>
                    <text class="error"
                      >流程结束，申请人不可在此流程上再进行修改</text
                    >
                  </template>
                </u-cell-item>
              </u-cell-group>
            </view>
          </u-form-item>
          <text class="u-m-t-30 block font-bold u-font-32 u-content-color"
            >审批意见</text
          >
          <u-form-item prop="comment">
            <view class="approve-content">
              <u-input v-model="form.comment" type="textarea" :height="200" />
            </view>
          </u-form-item>
        </u-form>
      </view>
    </view>
    <setMember
      ref="refSetmember"
      :memberType="form.dynamicParam"
      :choosedKeys="form.approvalParamList"
      :labels="labels.length && labels[0] ? labels : []"
      @submit="chooseSubmit"
    ></setMember>
    <u-modal
      v-model="showModal"
      :show-cancel-button="true"
      @confirm="submit(1)"
    >
      <view class="slot-content">
        <rich-text :nodes="modalContent"></rich-text>
      </view>
    </u-modal>

    <view class="btn-box">
      <u-button
        shape="circle"
        type="primary"
        :loading="confirmLoading"
        @click="submit()"
        >确定</u-button
      >
    </view>
  </view>
</template>
<script lang="ts" setup>
import cellSelectGroup from '@/components/cellSelect/cellSelectGroup.vue';
import cellSelectItem from '@/components/cellSelect/cellSelectItem.vue';
import { onLoad } from '@dcloudio/uni-app';
import setMember from '@/pages/approval/components/setMember.vue';
import { getNextNode } from '@/api/modules/flow';
import { cellClick } from '@/hooks/useBack';
import {
  workflowOperateProcessFundExpend,
  getExcessAmount,
} from '@/api/modules/finance';

const refSetmember = ref();
const hideReturn = ref<boolean>(false);
const showMember = () => {
  refSetmember.value.show();
};

const form = ref<any>({
  result: 1,
  dynamicParam: 0,
  nodeId: undefined,
  comment: '同意',
  approvalParamList: [],
});

const labels = ref<any[]>([]);
const chooseSubmit = (e: any) => {
  const { type, data, labels: labelList } = e;
  form.value.approvalParamList = data;
  form.value.dynamicParam = type;
  labels.value = labelList;
  console.log(form.value);
};

// 获取下一节点审批人
const hasNextNode = ref(true);
const targetKeyName = ref('');
const getNextNodeInfo = () => {
  getNextNode({
    taskId: publicTaskId.value,
  }).then((res: any) => {
    if (Object.keys(res).length === 0 || !res.nodeId) {
      hasNextNode.value = false;
    }
    targetKeyName.value = res?.targetKeyName;
    form.value.dynamicParam =
      res.approvalParamType && res.approvalParamType === 'PRE' ? 0 : 1;
    const names = (res.approvalParamName || '').split('、');
    labels.value = names;
    form.value.approvalParamList = res.approvalParamValue || [];
    form.value.nodeId = res.nodeId || undefined;
  });
};

const refForm = ref();
const confirmLoading = ref(false);
const workflowOperate = [0, 1, 2];
const showModal = ref<boolean>(false);
const modalContent = ref<string>('');
const submit = (type: number) => {
  refForm.value
    .validate((valid: boolean) => {
      if (valid) {
        const resultTypeList =
          approvalInfo.value.resultTypeList || workflowOperate;
        confirmLoading.value = true;
        const workflowIdByKey = approvalInfo.value.workflowIdByKey;
        if (form.value.result === 1) {
          const params: any = {
            [workflowIdByKey]: publicTaskId.value,
            comment: form.value.comment,
            workflowOperate: resultTypeList[1],
          };
          if (hasNextNode.value) {
            if (form.value.approvalParamList.length === 0) {
              uni.showToast({
                title: '请选择审批人',
                icon: 'none',
                duration: 2000,
              });
              confirmLoading.value = false;
              return;
            }
            params.approvalNodeInfo = {
              nodeId: form.value.nodeId,
              dynamicParam: form.value.dynamicParam === 0 ? 'PRE' : 'ROLE',
              approvalParamList: form.value.approvalParamList,
            };
          }
          if (type !== 1) {
            getExcessAmount({ expendId: publicTaskId.value }).then(
              (res: any) => {
                if (res.excess) {
                  modalContent.value = `<div style='padding:20px;'>
                <span>该申请单申请支出的金额已超出该费用类型</span>
                <span style='color:#ff4d4f;font-weight:bold;'>当前实际可用结余，超出金额为[${res.excessAmount}]元</span>
                <span>，请确认是否同意?</span>
                </div>`;
                  showModal.value = true;
                } else {
                  flowApprovalUrl[approvalInfo.value.flowurl](params)
                    .then(() => {
                      gotoTaskDetails();
                    })
                    .catch((e: any) => {
                      if (e.msg === '全部文件签署完成才能审批同意!') {
                        setTimeout(function () {
                          uni.setStorageSync('toFileList', '1');
                          gotoTaskDetails();
                        }, 500);
                      }
                    });
                }
                confirmLoading.value = false;
              }
            );
            return;
          }
          flowApprovalUrl[approvalInfo.value.flowurl](params)
            .then(() => {
              confirmLoading.value = false;
              gotoTaskDetails();
            })
            .catch((e: any) => {
              if (e.msg === '全部文件签署完成才能审批同意!') {
                setTimeout(function () {
                  uni.setStorageSync('toFileList', '1');
                  gotoTaskDetails();
                }, 500);
              }
              confirmLoading.value = false;
            });
        } else if (form.value.result === 0) {
          flowApprovalUrl[approvalInfo.value.flowurl]({
            [workflowIdByKey]: publicTaskId.value,
            comment: form.value.comment,
            workflowOperate: resultTypeList[form.value.result],
          })
            .then(() => {
              confirmLoading.value = false;
              gotoTaskDetails();
            })
            .catch(() => {
              confirmLoading.value = false;
            });
        } else if (form.value.result === 2) {
          flowApprovalUrl[approvalInfo.value.flowurl]({
            [workflowIdByKey]: publicTaskId.value,
            comment: form.value.comment,
            workflowOperate: resultTypeList[form.value.result],
          })
            .then(() => {
              confirmLoading.value = false;
              gotoTaskDetails();
            })
            .catch(() => {
              confirmLoading.value = false;
            });
        }
      }
    })
    .catch(() => {});
};
const resultChange = (e: number) => {
  switch (e) {
    case 0:
      form.value.comment = '退回';
      break;
    case 1:
      form.value.comment = '同意';
      break;
    case 2:
      form.value.comment = '拒绝';
      break;
    default:
      break;
  }
};

const gotoTaskDetails = () => {
  cellClick();
};

const publicTaskId = ref('');
const taskType = ref();
const approvalInfo = ref<any>();
const flowApprovalUrl: any = {
  fundExpend: workflowOperateProcessFundExpend,
};
onLoad(() => {
  const { id, approvalInfo: info } = (uni as any).$Router.getQuery();

  console.log((uni as any).$Router.getQuery());
  hideReturn.value = false;
  if (info.hideReturn) {
    hideReturn.value = true;
  }

  approvalInfo.value = info;

  publicTaskId.value = id || '';
  taskType.value = info.taskType;
  getNextNodeInfo();
});
</script>
<style lang="scss">
.block {
  display: block;
}
.page-content {
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 140rpx);
  .form-show {
    overflow: auto;
  }

  .next-point {
    border-radius: 30rpx;
    overflow: hidden;
  }
}
.btn-box {
  // position: absolute;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
  position: fixed;
  // bottom: 0;
  z-index: 10;
}
.u-card {
  padding: 0;
  margin: 0 !important;
  .cell-item {
    border-color: transparent;
  }
}
.u-form-item {
  padding-bottom: 0 !important;
}
.approve-content {
  background-color: #fff;
  border-radius: 30rpx;
  padding: 20rpx;
}
</style>
